package com.crape.common.mail;

import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Component;
import org.springframework.ui.velocity.VelocityEngineUtils;

/**
 * @author TaoMing 2012-5-16上午11:10:28
 * @author chenkaibj7051
 */
@Component
public class EmailService {

    private EmailAppConfig emailAppConfig;
    private VelocityEngine velocityEngine;

    @Autowired
    public void setEmailAppConfig(EmailAppConfig emailAppConfig) {
        this.emailAppConfig = emailAppConfig;
    }

    @Autowired
    public void setVelocityEngine(VelocityEngine velocityEngine) {
        this.velocityEngine = velocityEngine;
    }

    public void sendEmail(final Map<String, Object> model, final String subject, final String vmfilePath,
                          final String[] mailTo, final String[] files, final String[] ccEmail) {
        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "GBK");
                message.setTo(mailTo);// 接收方的email地址
                message.setCc(ccEmail);//抄送的email地址
                message.setSubject(subject);// 设置邮件主题
                message.setFrom(emailAppConfig.getUserName());// 设置发送方地址
                String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, vmfilePath, "UTF-8", model);
                message.setText(text, true);
            }
        };
        JavaMailSender mailSender = emailAppConfig.mailSender();
        mailSender.send(preparator);// 发送邮件
    }
}
